<template>
  <div class="describe-body">
    <div class="flex justify-end">
      <slot name="handle"></slot>
    </div>
    <TabLanguage
      @languageList="changeLanguage"
      @activeLang="activeLang"
      @translation="hanldeTranslation"
      v-model="descriptionList"
      :disabled="disabled"
    ></TabLanguage>
    <div
      :class="item.language_id == languageActive ? 'show' : 'hidden'"
      v-for="(item, index) in descriptionList"
      :key="index"
    >
      <el-card class="box-card pb-0">
        <div class="mb-3 flex items-center title">
          产品标题
          <p class="text-xs ml-2 text-[#CCC]">
            <svg-icon icon-class="hint_line" class="inline-block" />
            eBay标题最长80个字符，速卖通128个字符，wish300个字符。
          </p>
        </div>
        <el-input
          v-model="item.spu_title"
          :autosize="{ minRows: 4, maxRows: 10 }"
          type="textarea"
          placeholder="请输入"
          :disabled="disabled"
        />
      </el-card>
      <el-card class="box-card" v-if="item.language_id == 1">
        <div class="mb-3 flex justify-between title">
          <div class="flex items-center">
            销售属性
            <p class="text-xs ml-2 inline-block text-[#CCC]">
              <svg-icon icon-class="hint_line" class="inline-block" />
              需提前维护好系统分类对应的销售属性模板
            </p>
          </div>
          <el-select
            class="!w-[160px]"
            v-model="item.attribute_template_id"
            collapse-tags
            placeholder="请选择属性模版"
            @change="changeAttribute($event, item)"
            :disabled="disabled"
          >
            <el-option
              :label="i.template_name"
              :value="i.id"
              v-for="(i, k) in attributeList"
              :key="k"
            />
          </el-select>
        </div>
        <div
          class="flex justify-start flex-wrap"
          v-if="item.attribute_template_value && attribute_template_value.length"
        >
          <div
            class="mx-2 flex flex-col w-60 mb-4"
            v-for="(i, k) in item.attribute_template_value"
            :key="k"
          >
            <div class="">{{ i.label_name }}</div>
            <el-input v-model.trim="i.value" placeholder="名称" :disabled="disabled" />
          </div>
        </div>
      </el-card>
      <el-card class="box-card pb-0">
        <div class="mb-3 flex items-center justify-between title">
          <div>关键词组</div>
          <div>
            <el-button link type="primary" :disabled="disabled">清空</el-button>
            <el-button @click="copyKeyword(item.keyword)">
              <svg-icon icon-class="copy" class="inline-block" /> 拷贝描述</el-button
            >
          </div>
        </div>
        <el-input
          v-model="item.keyword"
          :autosize="{ minRows: 4, maxRows: 10 }"
          type="textarea"
          placeholder="请输入"
          :disabled="disabled"
        />
      </el-card>

      <el-card class="box-card pb-0">
        <div class="relative">
          <div class="flex justify-start flex-shrink-0 mb-2" style="white-space: nowrap">
            <div
              class="ml-1 px-5 py-1 cursor-pointer inactiveClass"
              :class="{ activeClass: descriptionActive === i.value }"
              v-for="(i, k) in tabList"
              :key="k"
              @click="changeTab(i.value)"
            >
              {{ i.name }}
            </div>
          </div>
          <div v-if="descriptionActive == 1" :key="index + '1'">
            <template v-if="disabled">
              <div class="min-h-[100px]" v-html="item.detail_description"></div>
            </template>
            <template v-else>
              <WangEditor v-model="item.detail_description" />
            </template>
          </div>
          <div v-if="descriptionActive == 2">
            <template v-if="disabled">
              <div class="min-h-[100px]" v-html="item.text_description"></div>
            </template>
            <template v-else>
              <WangEditor v-model="item.text_description" />
            </template>
          </div>
          <div v-if="descriptionActive == 3">
            <template v-if="disabled">
              <div class="min-h-[100px]" v-html="item.highlights_description"></div>
            </template>
            <template v-else>
              <WangEditor v-model="item.highlights_description" />
            </template>
          </div>
          <div v-if="descriptionActive == 4">
            <template v-if="disabled">
              <div class="min-h-[100px]" v-html="item.package_description"></div>
            </template>
            <template v-else>
              <WangEditor v-model="item.package_description" />
            </template>
          </div>
          <div v-if="descriptionActive == 5">
            <template v-if="disabled">
              <div class="min-h-[100px]" v-html="item.mobile_description"></div>
            </template>
            <template v-else>
              <WangEditor v-model="item.mobile_description" />
            </template>
          </div>
          <el-button class="absolute right-0 top-1" @click="copy(descriptionActive)">
            <svg-icon icon-class="copy" class="inline-block" /> 拷贝描述</el-button
          >
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup name="Describe">
import TabLanguage from "./TabLanguage.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { getClassificationAttribute } from "./api";
import { translationBatch } from "@/api/index";
import { computed, onMounted, reactive } from "vue";
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
// const { languageOptions } = storeToRefs(commonStore);
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:modelValue", "update:form"]);
let handleType = reactive(inject("handleType"));
let formData = reactive(inject("form"));

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const languageOptions = computed(() => {
  if (!commonStore.languageOptions) {
    commonStore.getLanguageList();
  }
  return commonStore.languageOptions || [];
});

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/product-description"))
  );
});

const data = reactive({
  tabList: [
    {
      name: "产品详情描述",
      value: 1,
    },
    {
      name: "纯文本描述",
      value: 2,
    },
    {
      name: "亮点描述",
      value: 3,
    },
    {
      name: "包裹描述(信息)",
      value: 4,
    },
    {
      name: "移动端描述",
      value: 5,
    },
  ],
});

const { tabList } = toRefs(data);

// 全部数据
const descriptionList = computed({
  get: () => {
    return props.modelValue || [];
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

let form = ref({});
const selectAttributes = ref([]);
// 选择语言
const changeAttribute = (val, row) => {
  attributeList.value.forEach((item) => {
    if (item.id == val) {
      row.attribute_template_value = item.attribute;
    }
  });
};
// 语言对应数据
const languageActive = ref(1);
// 描述选中项
const descriptionActive = ref(1);
// 切换语言
const changeLanguage = (list, active) => {
  languageActive.value = active;
  console.log(active);
  descriptionList.value = descriptionList.value.map((i) => {
    i.show = false;
    list.forEach((j) => {
      if (i.language_id == j.language_id) {
        i.show = true;
      }
    });
    return i;
  });
};
const activeLang = (act) => {
  languageActive.value = act;
};

const init = () => {
  let list = languageOptions.value;
  let initList = [];
  list &&
    list.forEach((item) => {
      initList.push({
        spu_title: "",
        detail_description: "",
        text_description: "",
        highlights_description: "",
        package_description: "",
        mobile_description: "",
        keyword: "",
        language_id: item.id,
        language: item.name,
        short_name: item.short_name,
        show: item.id == 1 || item.id == 2 ? true : false,
        spu_id: formData.value.spu_id,
      });
    });
  let newInitList = initList.map((i) => {
    descriptionList.value.map((j) => {
      if (i.language_id == j.language_id) {
        i = {
          ...i,
          ...j,
          show: true,
        };
      }
    });
    return i;
  });
  console.log("newInitList");
  console.log(newInitList);

  descriptionList.value = newInitList;
};
const attributeList = ref([]);

onMounted(() => {
  init();
  getAttribute();
});

const getAttribute = () => {
  getClassificationAttribute({
    attribute_class: formData.value.spu_category,
  }).then((res) => {
    attributeList.value = res.data;
    selectAttributes.value = [];
  });
};
// 拷贝词组
const copyKeyword = (value) => {
  if (!value) return false;
  proxy.copy(value);
};
// 拷贝描述
const copy = (type) => {
  const obj = {
    1: "detail_description",
    2: "text_description",
    3: "highlights_description",
    4: "package_description",
    5: "mobile_description",
  };
  if (!form.value[obj[type]]) return false;
  proxy.copy(form.value[obj[type]]);
};
const hanldeTranslation = async () => {
  let target_lang = [];
  let arr = null;
  descriptionList.value.forEach((i) => {
    if (i.show && i.language_id != 1) {
      target_lang.push(i.short_name);
    }
    if (i.language_id == 1) {
      arr = [
        i.spu_title || "",
        i.keyword || "",
        i.detail_description || "",
        i.text_description || "",
        i.highlights_description || "",
        i.package_description || "",
        i.mobile_description || "",
      ];
    }
  });

  let languageArr = ["en"].concat(target_lang);
  let texts = {};
  languageArr.forEach((i) => {
    texts[i] = arr;
  });

  try {
    const res = await translationBatch({
      target_lang,
      texts,
    });
    descriptionList.value = descriptionList.value.map((i) => {
      if (res.data[i.short_name] && JSON.stringify(res.data[i.short_name]) != "[]") {
        i.spu_title = res.data[i.short_name][0];
        i.keyword = res.data[i.short_name][1];
        i.detail_description = res.data[i.short_name][2];
        i.text_description = res.data[i.short_name][3];
        i.highlights_description = res.data[i.short_name][4];
        i.package_description = res.data[i.short_name][5];
        i.mobile_description = res.data[i.short_name][6];
      }
      return i;
    });
    ElMessage.success(res.message);
  } catch (e) {
    throw Error(e);
  }
};

const changeTab = (value) => {
  descriptionActive.value = value;
};

defineExpose({ getAttribute });
</script>

<style lang="scss" scoped>
.describe-body {
  border: 1px solid #e6e7e9;
  // margin: 8px;
  .box-card {
    margin: 8px;
    padding: 10px 8px;
    box-shadow: none;
    &.pb-0 {
      :deep(.el-card__body) {
        padding-bottom: 0;
      }
    }
    .title {
      border-bottom: 1px dashed #e6e7e9;
      padding-bottom: 8px;
    }
  }
}
.inactiveClass {
  padding: 16px 24px;
  background: var(--base-small-bg-color);
  border-radius: 4px;
}

.activeClass {
  color: #3487ff;
  background: #eaf3ff;
  border-radius: 4px;
}
</style>
